package com.example.exception;

import com.example.common.util.R;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @Author: AlbertHPW
 * @Date: 2025/6/15 23:59
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    public R exceptionHandler(Exception e) {

        // 如果异常是MethodArgumentNotValidException类型
        if (e instanceof MethodArgumentNotValidException) {
            // 返回字段验证错误信息
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            return R.error(exception.getBindingResult().getFieldError().getDefaultMessage());
        }
        // 如果异常是EmosException类型
        else if (e instanceof EmosException) {
            EmosException exception = (EmosException) e;
            // 返回自定义异常信息
            return R.error(exception.getMsg());
        }
        // 如果异常是UnauthorizedException类型
        else if (e instanceof UnauthorizedException) {
            // 返回权限不足信息
            return R.error("你不具备相关权限");
        } else {
            // 返回后端执行异常信息
            return R.error("后端执行异常");
        }
    }
}
